var tt_someItemSelected = false;

/**
 * 输入的数据无效（即不是通过）
 * 
 * @type String
 */
var cls4autocomplete_novalid = "autocomplete_novalid";
var tt_autocomplete_title = "输入值后按回车键进行查询。不可以输入值后不进行选择！";

var tt_autocompleteValidator = tt.BV.ext({
	/**
	 * 验证的主方法
	 */
	v : function(trimedValue, indexOfElements, elements, field) {
		if (!trimedValue) {
			return true;
		}
		if (elements[indexOfElements].className
				.indexOf(cls4autocomplete_novalid) != -1) {
			return false;
		}
		return true;
	},
	getI18 : function(label, e, f, index, val) {
		return e.tt_auto_error_msg;
	}
});

function tt_autoeompleteSetup(acCfg) {
	acCfg.highlightclass = acCfg.highlightclass
			? acCfg.highlightclass
			: "talent_grid_highlight";

	var handler = new tt_autocompleteEventHandler(acCfg);
	acCfg.inputObj  = acCfg.inputObj ? acCfg.inputObj : document.getElementById(acCfg.inputid);
	var inputObj = acCfg.inputObj;
	
	//acCfg.contextpath + "/common/getPagerBySqlId.talent",                                         // 后台查询的url
	if (acCfg.sqlid) {
		acCfg.url = acCfg.contextpath + "/common/getPagerBySqlId.talent";
	}
	
	var dftPlaceText = "敲回车进行查询";
	if (acCfg.countofstartquery > 0){
		dftPlaceText = "输入" + acCfg.countofstartquery + "个字符后，敲回车进行查询"
	}
	var placetext = acCfg.placeholder || dftPlaceText;
	
	inputObj["placeholder"] = placetext;
	
//	$(inputObj).addClass(cls4autocomplete_novalid);
	talent.Util.addEventHandler(inputObj, "keyup", handler.h);
	
	if (acCfg.events) {
		for (var i  = 0; i < acCfg.events.length; i++) {
			talent.Util.addEventHandler(inputObj, acCfg.events[i], handler.h);
		}
	}
	

	inputObj.title = placetext;
	inputObj.tt_auto_error_msg = acCfg.title || tt_autocomplete_title;

    var co = document.createElement("div");
    document.body.appendChild(co);


	acCfg.containerObj = co;
	
	$(co).addClass("autocompleteContainer");
	
	//给field加render
	for (var ii = 0; ii < acCfg.fields.length; ii++) {
		if (!acCfg.fields[ii].dataCellRenderConfig) {
			acCfg.fields[ii].dataCellRenderConfig = {
				clazz : tt_autocompleteFieldRender,
				config : {
					"acCfg" : acCfg
				}
			}
		}
		
	}
	
	var _closeCallback = function(_acCfg) {
		this.h = function(){
			_acCfg.datas = null;
		};
		
	}
	
	var gridConfig = {
		container : co,         // 放置grid的容器对象
		name: acCfg.inputObj.id,
		url : acCfg.url,
		canClose: true,
		form : document.getElementById(acCfg.formid),                 // 要提交的form
		showHeader: acCfg.showHeader,
		closeCallback: new _closeCallback(acCfg).h,

		fields: acCfg.fields,
		ajaxConfig : acCfg.ajaxConfig,
		highlight: {}
	};
	gridConfig.postData = [{"name" : "isPagination",  "value" : acCfg.isPagination}, {"name" : "sqlId",  "value" : acCfg.sqlid}];  // 要求分页  acCfg.sqlid
	
	if (acCfg.gridConfig){
        talent.Util.copy(gridConfig, acCfg.gridConfig);
    } else{
        acCfg.gridConfig = {};
    }

	
	acCfg.grid = new talent.ui.Grid(gridConfig);
	
	if (!acCfg.skipValidate == true) {
		var v = new tt_autocompleteValidator();
		v.add(new tt.Field(null, null, acCfg.inputObj.id).setValidateOn(null));
	}
    $("body").bind("mousedown", new tt_acMouseDownOnbody(acCfg).h);
	
}

var tt_autocompleteEventHandler = function(acCfg) {
	this.h = function() {
		var inputObj = acCfg.inputObj;
		var e = window.event || arguments[0];
		
		var keyCode = e.keyCode;
		var trimValue = talent.Util.trim(inputObj.value);
//		inputObj.value = trimValue;
		
		if (keyCode != 13 && keyCode != 38 && keyCode != 40 && keyCode != 0) { // 不是(enter, Up down 没有按键) 这四种情况
			if (acCfg.lastInputObjValue == trimValue) {
				return;
			} else {
				acCfg.lastInputObjValue = trimValue;
			}
			
			$(inputObj).addClass(cls4autocomplete_novalid);
			
			for (var i in acCfg.mapping) {
				var e;
				if (talent_isSpecifiedType(i, "String")){
					e = document.getElementById(i);
				} else {
					e = i;
				}
				if (e != inputObj) {
					e.value = "";
				}
			}
			acCfg.datas = null;
//			return;
		}
		
		if (acCfg.datas) {
			return;
		}
		
		if (acCfg.beforeCheck) {
			var t = acCfg.beforeCheck.call(acCfg);
			if (t == false) {
				return;
			}
		}
		
		

		

		if (keyCode == 13 && tt_someItemSelected) { // enter
			// 是enter，并且已经有条目被选中了，此时需要关闭
			tt_hideAutocomplete(acCfg);
			tt_someItemSelected = false;
			$(inputObj).removeClass(cls4autocomplete_novalid);
			return;
		}

		tt_someItemSelected = false;
		
		
		if (trimValue.length < acCfg.countofstartquery) {
			alert("请输入" + acCfg.countofstartquery + "个字符后，再进行查询。");
			tt_hideAutocomplete(acCfg);
			return;
		}

		

		if (acCfg.datas && (keyCode == 38 || keyCode == 40)) {
			var index = 0;
			if (keyCode == 38) { // Up Arrow
				index = (--acCfg.currIndex);
			} else if (keyCode == 40) { // down Arrow
				index = (++acCfg.currIndex);
			}

			if (index >= acCfg.datas.length) {
				index = 0;
				acCfg.currIndex = index;
			} else if (index < 0) {
				index = (acCfg.datas.length - 1);
				acCfg.currIndex = index;
			}

			return;
		}
		
		talent.Util.copy(acCfg.containerObj, acCfg.props);
		talent.Util.setStyle(acCfg.containerObj, acCfg.styles);

        var pageSize = acCfg.gridConfig.pageSize || 20;
        talent.ui.GridProxy[acCfg.inputObj.id].reload(0, pageSize);
		
		var acContainer = acCfg.containerObj;
		var $inputObj = $(inputObj);
		var offset = $inputObj.offset();
		$(acContainer).css({
					left : offset.left + "px",
					top : offset.top + $inputObj.outerHeight() + "px"
				}).slideDown("fast");
	};
};

/**
 * 
 * @param {}
 *            acCfg
 * @param {}
 *            record
 */
var tt_autocompleteItemClicked = function(acCfg, record) {
	this.h = function(e1) {
		// {"personid_add":"personid", "personname_add":"personname"};
        var e = e1 || window.event;
		if (acCfg.callbackBeforeSetValue) {
			acCfg.callbackBeforeSetValue.call(window, record, acCfg);
		}
		for (var i in acCfg.mapping) {
			if (talent_isSpecifiedType(i, "String")){
				document.getElementById(i).value = record[acCfg.mapping[i]];
			} else {
				i.value = record[acCfg.mapping[i]];
			}
		}
		var inputObj = acCfg.inputObj;

		$(inputObj).removeClass(cls4autocomplete_novalid);
		if (e.type == 'click') {
			tt_hideAutocomplete(acCfg);
		} else if (e.type == 'keyup') {
			tt_someItemSelected = true;
		}
		tt.validateElement(inputObj);
		
		if (acCfg.callback) {
			acCfg.callback.call(window, record, acCfg);
		}
	};
};

	// this.config:{table:{}, row:{}, cell:{}, rowData:{},
	// field:{}, gridConfig:{}, gridContext:{}, rowIndex:{}, colIndex:{}}
 function tt_autocompleteFieldRender(conf) {
	var cloneConfig = {};
	talent.Util.copy(cloneConfig, conf);
	
	var record = cloneConfig.rowData;
	var cellVal = record[cloneConfig.field.name];
	
	if (cloneConfig.colIndex == 0) {
		var h = new tt_autocompleteItemClicked(cloneConfig.acCfg, record);
		talent.Util.addEventHandler(cloneConfig.cell, "click", h.h);
	}
	
	conf.acCfg.datas = cloneConfig.gridContext;
	var inputVal = cloneConfig.acCfg.inputObj.value;
	if (cellVal) {
		cloneConfig.cell.innerHTML = cellVal.replace(
					new RegExp(inputVal, "g"), "<span class='autocomplete_highlight'>" + inputVal + "</span>");
	} else {
		cloneConfig.cell.innerHTML = "";
	}
}


function tt_hideAutocomplete(acCfg) {
	try {
		acCfg.datas = null;
		$(acCfg.containerObj).slideUp("fast");   //fast
		
	} catch (e) {

	}
	// $("body").unbind("mousedown", tt_onBodyDown4Autocomplete);
}

function tt_acMouseDownOnbody(acCfg){
    this.h = function(e1) {
//        for (var i in acCfg.mapping) {
//            if (talent_isSpecifiedType(i, "String")){
//                document.getElementById(i).value = "";
//            } else {
//                i.value = "";
//            }
//        }
        var e = e1 || window.event;
        if(e.target == acCfg.inputObj){
            return;
        } else {
            var tem = e.target;

            while (tem != null && (tem = tem.parentNode) != document.body) {
                if (tem == acCfg.containerObj) {
                    break;
                }
            }
            if (tem == null || tem == document.body){
                tt_hideAutocomplete(acCfg);
            }
        }
    };
}